<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    :bodyStyle="bodyStyle"
    style="top:15%;height: 70%;overflow-y: hidden"
  >
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel">
        关闭
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" id="customerModal">
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="申请人">
            <a-select
              v-decorator.trim="['applicant']"
              allowClear
              placeholder="选择申请人"
              showSearch
              optionFilterProp="children"
            >
              <a-select-option v-for="(item, index) in personList" :key="index" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="内部编码">
            <a-input placeholder="请输入内部编码" v-decorator.trim="['contractCode']" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="合同编号">
            <a-input placeholder="请输入合同编号" v-decorator.trim="['contractNum']" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户名称">
            <a-input placeholder="请输入客户名称" v-decorator.trim="['customerName']" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="审批表">
            <a-upload
              name="file"
              :multiple="false"
              :headers="tokenHeader"
              :action="importExcelUrl"
              :showUploadList="false"
              v-decorator.trim="['approvalForm']"
              @change="myhandleImportExcel"
            >
              <a-button> <a-icon type="upload" />上传</a-button>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import pick from 'lodash.pick'
import { addCustomer, personList, checkSupplier, addContractApproval, putContractApproval } from '@/api/api'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { autoJumpNextInput } from '@/utils/util'
export default {
  name: 'ContractApprovalModal',
  mixins: [JeecgListMixin],
  data() {
    return {
      title: '操作',
      visible: false,
      defaultFileList: null,
      model: {},
      personList: [],
      isReadOnly: false,
      bodyStyle: {
        padding: '20',
        height: window.innerHeight * 0.5 + 'px',
        'overflow-y': 'auto'
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      url: {
        importExcelUrl: '/systemConfig/upload' + '?' + `biz=ht`
      },
      form: this.$form.createForm(this),
      validatorRules: {
        name: {
          rules: [
            { required: true, message: '请输入名称!' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
            { validator: this.validateSupplierName }
          ]
        }
      }
    }
  },
  mounted() {
    personList().then(res => {
      if (res.code == 200) {
        this.personList = res.data
      } else {
        this.$message.warning(res.message)
      }
    })
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`
      // return `api${this.url.importExcelUrl}`
    }
  },
  methods: {
    /* 导入 */
    myhandleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200 || info.file.response.code === 10000) {
            this.$message.success(`${info.file.name} 文件上传成功` || info.file.response.data)
            this.defaultFileList = info.file.response.data
            console.log('defaultFileList:', this.defaultFileList)
          } else {
            this.$message.warning(info.file.response.message)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.data}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    add() {
      this.edit()
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.defaultFileList = this.model.approvalForm
      console.log(this.model)
      this.personList.map(item => {
        item.id == this.model.applicant ? (this.model.applicant = item.name) : ''
      })
      this.$nextTick(() => {
        this.form.setFieldsValue(
          pick(this.model, 'customerName', 'contractCode', 'contractNum', 'approvalForm', 'applicant')
        )
        autoJumpNextInput('customerModal')
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(values)
          if (this.model.beginNeedGet && this.model.beginNeedPay) {
            that.$message.warn('期初应收和期初应付不能同时输入')
            that.confirmLoading = false
            return
          }
          formData.approvalForm = this.defaultFileList
          let obj
          if (!this.model.id) {
            obj = addContractApproval(formData)
          } else {
            formData.id = this.model.id
            obj = putContractApproval(formData)
          }
          obj
            .then(res => {
              if (res.code === 200 || res.code === 10000) {
                  this.$message.success('保存成功')
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateSupplierName(rule, value, callback) {
      let params = {
        name: value,
        type: '客户',
        id: this.model.id ? this.model.id : 0
      }
      checkSupplier(params).then(res => {
        if (res && res.code === 200) {
          if (!res.data.status) {
            callback()
          } else {
            callback('名称已经存在')
          }
        } else {
          callback(res.data)
        }
      })
    }
  }
}
</script>
<style scoped>
.ant-spin-container {
  height: 200px;
}
</style>
